from google.appengine.ext import db

class Email(unicode):
  """ Represeents email address -- case insensitive for comparison
  
  >>> Email('abc@xyz.com') == Email(' ABC@xyz.com  ')
  True
  >>> Email('abc@xyz.com') == Email('a@bcxyz.com')
  False
  >>> Email('abc@xyz.com') == 'abc@XYZ.com'
  True
  >>> Email('abc@xyz.com') == None
  False
  
  """
  @classmethod
  def clean(self, value):
    if value:
      return value.strip().lower()
    else:
      return ''
  
  def __eq__(self, x):
    return Email.clean(self) == Email.clean(x)
  
  def __ne__(self, x):
    return not self.__eq__(x)
  
  def __repr__(self):
    return "Email('%s')" % self

class EmailProperty(db.Property):
  """ Stores email with custom validation """
  data_type = Email
  
  verbose_type = 'Email Address'
  
  def get_value_for_datastore(self, model_instance):
    value = super(EmailProperty, self).\
      get_value_for_datastore(model_instance)
    if isinstance(value, Email):
      return unicode(value)
    return value
    
  def get_value_for_lookup(self, model_instance):
    value = self.get_value_for_datastore(model_instance)
    if value:
      return Email.clean(value)
  
  def get_value_for_sort(self, model_instance):
    return self.get_value_for_lookup(model_instance)
  
  def validate(self, value):
    if not value:
      return None
    return Email(value)
  
  def make_value_from_datastore(self, value):
    if value is None:
      return None
    return Email(value)
